/**
 * 定义ui公共模块
 */
(function(window, angular, undefined){

	var component = angular.module('water.common.component.zhuhaiStationList',['water.entity.domain','water.common.formCheck']);

	component.directive("zhuhaiStationList", function($timeout,$rootScope,$wdp) { 
		  return {
			transclude: false,    // 不复制原始HTML内容 
		    restrict: "A",        // 指令是一个元素 (并非属性) 
		    require : "ngModel",
		    replace: true,        // 使用模板替换原始标记 
		    scope: {              // 设置指令对于的scope 
		      height:"@",
		      model:"=ngModel",
		      pollType:"@",
		      change:"&ngChange",
		      isReport:"@",
		      isCompany:"@",
		      companySelecterText:"@"
		    }, 
		    template:function(){
		    	var userid="";
		    	
		    	try {
		    		userid = $rootScope.currentUser.C_USERNAME;
				} catch (e) {
					// TODO: handle exception
				}
		    	
/*		    	var stateHtml = "<tr >\n" + 
		    	"            <td colspan=\"2\" class=\"left tip\">\n" + 
		    	"              <span ng-click=\"changeStationStatus(0)\" class=\"gsstation_zc0 text\" ng-if='waterType ==3' ng-class=\"queryObj.stationStatus=='0'?'selected':''\">正常({{statusStatistics.staNormal}})</span>\n" + 
		    	"   		   <span ng-click=\"changeStationStatus(0)\" class=\"station_zc0 text\" ng-if='waterType !=3' ng-class=\"queryObj.stationStatus=='0'?'selected':''\">正常({{statusStatistics.staNormal}})</span>\n" + 
		    	"              <span ng-click=\"changeStationStatus(1)\" class=\"station_cb1 text\" ng-class=\"queryObj.stationStatus=='1'?'selected':''\">超标({{statusStatistics.staOverproof}})</span>\n" + 
		    	"              <span ng-click=\"changeStationStatus(2)\" class=\"station_yc2 text\" ng-class=\"queryObj.stationStatus=='2'?'selected':''\">异常({{statusStatistics.staExecption}})</span>\n" + 
		    	"              <span ng-click=\"changeStationStatus(3)\" class=\"station_gz3 text\" ng-class=\"queryObj.stationStatus=='3'?'selected':''\">故障({{statusStatistics.staFault}})</span>\n" + 
		    	"            </td>\n" + 
		    	"          </tr>\n" ;*/
				var stateHtml="";
		    	
		    	if(userid == "aomen"){
		    		stateHtml = "";
		    	}
		    	
		    	var html = "<div>\n"+
		    	"<div class=\"zs-form-tabs\">\n" +
		    	"      <table class=\"zs-form-tab\">\n" + 
		    	"        <tbody>\n" + 
		    	"          <tr ng-if='isCompany==\"true\"'>\n" + 
		    	"            <td class=\"right top\" width=\"25%\">{{companySelecterText}}：</td>\n" + 
		    	"            <td>\n" + 
		    	"              <company-selecter poll_type='{{pollType}}' ng-model=\"companySelected\" ng-change=\"changeCompany\"></company-selecter>\n" + 
		    	"            </td>\n" + 
		    	"          </tr>\n" + 
		    	"          <tr>\n" + 
		    	"		   <tr ng-if='waterType == 2 || waterType == 4'>"+
				"			 <td class='right top' width='25%'>所属政区：</td>"+
				"			 <td>"+
				"				<com-single-check data='area' ng-model='queryObj.DISTRICT' ng-change='queryClick'></com-single-check>"+
				"			 </td>"+
				"			</tr>"+
		    	"            <td class=\"right\">站点名称：</td>\n" + 
		    	"            <td colspan=\"2\"><input class=\"zs-input\" type=\"text\"\n" + 
		    	"              style=\"width: 145px;\" ng-model='queryObj.STATION_NAME'> <input\n" + 
		    	"              type=\"button\" name=\"ok\" ng-click=\"queryClick();\" value=\"查询\"\n" + 
		    	"              class=\"zs-btn\"></td>\n" + 
		    	"          </tr>\n" + 
		    	"<tr ng-if='isReport==\"true\"'>\n" +
		    	"     <td class=\"right\">监测项：</td>\n" + 
		    	"     <td style=\"width:224px\">\n" + 
		    	"       <div><input href=\"#\" class=\"zs-btn\" ng-show=\"!parmListShow\" ng-click=\"parmListShow = true\" value=\"展开监测项\"/></div>\n" + 
		    	"       <div id=\"parm_list\" ng-show=\"parmListShow\">\n" + 
		    	"         <label repeat-finish ng-finish=\"pollLoadFinish()\" class=\"report_poll_list\" ng-repeat=\"curRow in pollList\">\n" + 
		    	"           <input name=\"parmToCheck\" checked ng-click=\"pollLoadFinish()\" unit=\"{{curRow.UNIT}}\" couunit=\"{{curRow.COU_UNIT}}\" value=\"{{curRow.CODE}}\" parmText=\"{{curRow.NAME}}\" class=\"zs-btn\" type=\"checkbox\" style=\"padding-right:2px\"/>\n" + 
		    	"           {{curRow.NAME}}\n" + 
		    	"         </label>\n" + 
		    	"       </div>\n" + 
		    	"       <div style=\"clear: both;\"><input type=\"button\" class=\"zs-btn\" href=\"#\" ng-show=\"parmListShow\" value=\"全不选\" ng-click=\"unSelectParms()\"/></div>\n" + 
		    	"       <div style=\"clear: both;\"><input type=\"button\" class=\"zs-btn\" href=\"#\" ng-show=\"parmListShow\" value=\"收&nbsp;&nbsp;&nbsp;起\" ng-click=\"parmListShow = false\"/></div>\n" + 
		    	"     </td>\n" + 
		    	" </tr>"+
		    	stateHtml +
		    	"<tr  ng-if='waterType == 2 || waterType == 4' >\n" +
		    	" <td class=\"right\">数据来源：</td>\n" + 
		    	" <td colspan=\"2\" class=\"left\" >\n" + 
		    	"   <div class=\"tip\" >\n" + 
		    	"     <span class=\"station_tb4 text\">&nbsp;同步</span>\n" + 
		    	"     <span class=\"station_ftb5 text\">&nbsp;实时传输</span>\n" + 
		    	"   </div>\n" + 
		    	" </t>" +
		    	"        </tbody>\n" + 
		    	"      </table>\n" + 
		    	"    </div>"+
		    	"<div class=\"zs-data-list\"  ng-style=\"{height:height}\" style=\"overflow: auto;\">\n" +
		    	"      <div ng-repeat=\"curRow in stationList\" >\n" + 
		    	"		<div class=\"list\" ng-if=\"curRow.COMPANY_NAME_HAS_PARENT == null && curRow.COMPANY_NAME != null\" ng-click='companyClick(curRow.WWTP_ID)' guid='{{curRow.WWTP_ID}}' style=\"background-color: #e9e9e9;\">\n" +
		    	" 			<div style=\"float: left;cursor: pointer;width:200px;\">\n" + 
		    	"            <div style='font-size: 12px;' ng-style={'min-height':result.COMPANY_PHOTO?'45px':'20px'} >{{curRow.COMPANY_NAME}}</div>\n" + 
		    	"          </div>\n" + 
		    	"          <div style=\"float: right\">\n" + 
		    	"			<div class=\"img-wrap\">\n" +
		    	"              <a href=\"#\">\n" + 
		    	"                <img ng-if=\"result.COMPANY_PHOTO\" ng-src=\"{{hostBase}}{{result.COMPANY_PHOTO | firstImgUrl}}\"\n" + 
		    	"                  style=\"width: 50px; height: 40px;\">\n" + 
		    	"              </a>\n" + 
		    	"            </div>"+
		    	"          </div>\n" + 
		    	"        </div>" +
		    	"		<div ng-class=\"{list:true,selected:curRow.CODE==model.CODE}\"  ng-click = \"selectStation(curRow)\" company_guid='{{curRow.WWTP_ID}}'"+ 
		    	"				ng-style=\"{'padding-left':(curRow.COMPANY_NAME_HAS_PARENT == null && curRow.COMPANY_NAME == null?'0px':'15px')}\">"+
		    	"        <div style=\"float: left;cursor: pointer;width:140px;\">\n" + 
		    	"          <div style='font-size: 12px;'>" +
		    	"				<span>{{curRow.NAME}}</span>" +
		    	"		</div>\n" + 
		    	"        </div>\n" + 
		    	"        <div style=\"float: right\">\n" + 
		    	"          <div class=\"img-wrap\">\n" + 
		    	"            <a href=\"#\">\n" + 
		    	"              <img ng-if=\"curRow['PHOTO']\"\n" + 
		    	"                ng-src=\"{{hostBase}}{{curRow['PHOTO'] | firstImgUrl}}\"\n" + 
		    	"                onclick=\"imgShow($(this))\"\n" + 
		    	"                style=\"width: 50px; height: 40px;\">\n" + 
		    	"              <img ng-if=\"!curRow['PHOTO']\"\n" + 
		    	"                ng-src=\"{{wdpjsRootPath}}wdp/images/zs-photo.png\"\n" + 
		    	"                style=\"width: 50px; height: 40px;\">\n" + 
		    	"              </a>\n" + 
		    	"          </div>\n" + 
		    	"        </div>\n" + 
		    	"		<div ng-show='curRow.canOpen && openedStationDeviceNum != curRow.DEVICE_NUM && openedStationNo != curRow.CODE' style=\"float: right;margin-right:6px;\">未开启</div>"+
		    	"		<div ng-show='curRow.canOpen && openedStationDeviceNum != curRow.DEVICE_NUM && openedStationNo == curRow.CODE' style=\"float: right;margin-right:6px;\">切换中</div>"+
		    	"		<div ng-show='curRow.canOpen && openedStationDeviceNum == curRow.DEVICE_NUM' style=\"float: right;margin-right:6px;\">当前管路</div>"+
		    	"      </div>\n" + 
		    	"	</div>"+
		    	"</div>"+
		    	"</div>";
		    	return html;
		    },
		    link: function ($scope, element, attrs, controller) {
		    	$wdp.stationListReady = false;
		    	$scope.queryObj = {};
		    	$scope.area={};
		    	$scope.waterType = getWaterType();
		    	$scope.hostBase = getHostBase();
		    	$scope.wdpjsRootPath = getJsBasePath();
		    	$scope.callNoticeParmChange = null;
		    	$scope.openedStationNo;
		    	$scope.openedStationDeviceNum;
		    	$scope.userid="";
		    	
		    	try {
		    		$scope.userid = $rootScope.currentUser.C_USERNAME;
				} catch (e) {
					// TODO: handle exception
				}
		    	
		    	/**
				  * stationNoToOpen 要开启的站点编号
		    	 */
		    	$scope.openStation = function(stationNoToOpen,name){
		    		$.messager.confirm("确认","确定要切换管路么？",function(r){
		    			if(r){
		    				var queryObj = {
				    				stationNoToOpen:stationNoToOpen
				    		};
				    		$waterDataCommon.post("/ZhuhaiMonitorStation/stationOpen.do",queryObj).then(function(result){
				    			$.messager.alert("设置成功","管道将在下一个测量周期切换到“"+name+"”","info");
				    		});
		    			}
					});
		    	}
		    	
		    	$scope.getOpenedStationNo = function(){
		    		$waterDataCommon.post("/ZhuhaiMonitorStation/getOpenedStationNo.do",{}).then(function(result){
		    			$scope.openedStationNo = result.openedStationNo;
		    			$scope.openedStationDeviceNum = result.openedStationDeviceNum;
		    		});
		    	}
		    	
		    	$scope.queryStation = function(){
		    		$scope.queryObj.BUILD_STATUS = '0';
		    		$waterDataCommon.post("/MonitorStation/getListWithCompany.do",$scope.queryObj).then(function(result){
		    			var stationList = result.data;
		    			for(var i=0;i<stationList.length;i++){
		    				var station = stationList[i];
		    				var name = station.NAME;
		    				if(name.indexOf("广昌") > -1 && $scope.userid != 'aomen'){
		    					stationList[i].canOpen = true;
		    				}
		    			}
		    			$scope.stationList = stationList;
		    			$wdp._cache_stationList = stationList;
		    			$scope.selectStation($scope.stationList[0]);
		    		});
		    		$waterDataCommon.post("/MonitorStation/getStatusStatistics.do",$scope.queryObj).then(function(result){
		    			$scope.statusStatistics = result;
		    			$wdp._cache_statusStatistics = result;
		    		});
		    		$waterDataCommon.post("/district/getDistrict.do").then(function(data){
						for(var i=0;i<data.qu.length;i++){
							data.qu[i].v=data.qu[i].NAME;
							data.qu[i].k=data.qu[i].CODE;
						}
						$scope.area = data.qu;
						$wdp._cache_area=data.qu;
		    		});
		    	}
		    	
		    	$scope.queryClick = function(){
		    		$scope.queryObj.stationStatus = "";
		    		$scope.queryStation();
		    	}
		    	/**
		    	 * 公司单击事件
		    	 */
		    	$scope.companyClick = function(companyGUID){
		    		var stataionDivs = $("div[company_guid='"+companyGUID+"']");
		    		stataionDivs.animate({height: 'toggle', opacity: 'toggle'}, "fast");
		    	}
		    	
		    	$scope.changeStationStatus = function(status){
					if($scope.queryObj.stationStatus == status){
						$scope.queryObj.stationStatus = "";
					}
					else{
						$scope.queryObj.stationStatus = status;
					}
					
					$scope.queryStation();
				}
		    	
		    	$scope.selectStation = function(station){
		    		$scope.model = station;
		    		$wdp._cache_station_selected_model = station;
		    		if(!$scope.model){
		    			return;
		    		}
		    		if($scope.isReport == "true"){
		    			//如果是报表模式，则再去获取站点的参数，参数获取到之后，再去通知参数变化了
		    			getStationPoll($scope.model.CODE);
		    		}
		    		else{
		    			//如果不是报表模式，则直接通知站点选择变化了
		    			noticeParmChange();
		    			$wdp.stationListReady = "true";
		    		}
		    		if($scope.change()){
		    			$scope.change()($scope.model);
		    		}
		    	}
		    	
		    	$scope.changeCompany = function(company){
					$scope.queryObj.WWTP_ID = company.companyCode;
					$scope.queryObj.companyName = company.companyName
					$scope.queryStation();
				}
		    	
		    	$scope.changeStationStatus = function(status){
					if($scope.queryObj.stationStatus == status){
						$scope.queryObj.stationStatus = "";
					}
					else{
						$scope.queryObj.stationStatus = status;
					}
					
					$scope.queryStation();
				}
		    	
		    	function getStationPoll(stationCode){
		    		$scope.pollList=[];
		    		if($scope.isReport == "true"){
		    			$waterDataCommon.getPageRows("/OnlineMonitor/getStationPollDict.do","stationPoll", {"STATION_ID":stationCode},100,1,function(data){
			    			$scope.pollList = data.data;
			    			if($scope.pollList == null || $scope.pollList.length < 1){
			    				noticeParmChange();
			    			}
						},null,null,false);
		    		}
		    	}
		    	
		    	//站点参数加载完成执行
				$scope.pollLoadFinish = function(){
					noticeParmChange();
					$wdp.stationListReady = "true";
				}
				
				/**
				 * 参数全不选
				 */
				$scope.unSelectParms = function(){
					$("input[name='parmToCheck']").removeAttr("checked");
				}
				
				/**
				 * 获取界面上勾选的参数
				 */
				function getReportParms(){
					if(!$scope.model){
						return;
					}
					var parmToCheckDom = $("input[name='parmToCheck']:checked");
					var parmToChecksStr = "";
					var parmToCheckList = [];
					
					for(var i=0;i<parmToCheckDom.length;i++){
						var parmCode = $(parmToCheckDom[i]).val();
						var parmText = "";
						var parmName = $(parmToCheckDom[i]).attr("parmText");
						var parmUnit = $(parmToCheckDom[i]).attr("UNIT");
						var parmCouUnit= $(parmToCheckDom[i]).attr("couunit");
						if(parmUnit){
							parmText = parmName + "(" + parmUnit + ")";
							parmCouText=parmName + "(" + parmCouUnit + ")";
						}
						else{
							parmText = parmName;
							parmCouText = parmName;
						}
						parmToChecksStr += $(parmToCheckDom[i]).val()+",";
						parmToCheckList.push({"name_original":parmCode,"name":parmCode.toUpperCase(),"text":parmText,parmName:parmName,"couunit":parmCouUnit,"unit":parmUnit});
					}
					$.cookie("parmToChecksStr",parmToChecksStr,{expires:7});
					var wwtpReportParm = {
								parmToChecksStr:parmToChecksStr,
								parmToCheckList:parmToCheckList,
								STATION_ID:$scope.model.CODE,
								STATION_NAME:$scope.model.NAME,
								MN:$scope.model.DEVICE_NUM
							};
					
					if($scope.pollList == null || $scope.pollList.length <1){
						wwtpReportParm.parmToChecksStr = "";
						wwtpReportParm.parmToCheckList = [];
					}
					
					return wwtpReportParm;
				}
		    	
		    	function noticeParmChange(){
		    		
		    		try {
		    			if($scope.callNoticeParmChange){
		    				clearTimeout($scope.callNoticeParmChange);
			    		}
					} catch (e) {
						console.log(e);
					}
		    		
					$scope.reportParms = getReportParms();
					$scope.$emit('dataPramChange', $scope.reportParms); 
				}
		    	
		    	//相应获取参数的事件
				$scope.$on('askedDataPramChange', function(event, data) {  
					noticeParmChange();
			    });
		    	
				if($wdp._cache_stationList){
					$scope.statusStatistics = $wdp._cache_statusStatistics;
					$scope.stationList = $wdp._cache_stationList;
					$scope.area=$wdp._cache_area;
		    		$scope.selectStation($wdp._cache_station_selected_model);
				}
				else{
					$scope.queryStation();
				}
				
				/**
				 * 这个的目的是，在多个状态，但是左边用的是同一个view和controller的情况下
				 * 在切换状态的时候，左边的controller不会再执行，会导致不会初始化
				 * 所以这里监听状态切换事件，在状态切换的时候，主动调一些方法
				 */
				$scope.$on("$stateChangeSuccess",function(){
					if($scope.waterType!='3'){
						$scope.callNoticeParmChange = setTimeout(function(){
							noticeParmChange();
						},500);
					}
				});
				$scope.getOpenedStationNo();
		    }
		  } 
		});
}(window, angular));